<template>
  <div class="map-container">
    <!-- 切换按钮 -->
    <div class="map-toggle">
      <el-radio-group v-model="mapMode" size="large">
        <el-radio-button label="articles">游记</el-radio-button>
        <el-radio-button label="disasters">灾害</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 自定义搜索框 -->
    <div class="search-box">
      <!-- 定位到当前位置按钮 -->
      <div class="location-button-container">
        <el-tooltip content="定位到当前位置" placement="bottom">
          <el-button circle :icon="Location" :loading="locating" @click="locateCurrentPosition"></el-button>
        </el-tooltip>
      </div>

      <el-input
        v-model="searchKeyword"
        placeholder="输入地址搜索"
        :disabled="searching"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" :loading="searching">
            搜索
          </el-button>
        </template>
      </el-input>
      <div v-if="searchResults.length > 0" class="search-results">
        <div
          v-for="(item, index) in searchResults"
          :key="index"
          class="search-result-item"
          @click="handleSelectSearchResult(item)"
        >
          <span class="result-name">{{ item.name }}</span>
          <span class="result-address">{{ item.address || item.district }}</span>
        </div>
      </div>
    </div>

    <el-amap
        class="amap-box"
        :zoom="mapConfig.zoom"
        :zooms="mapConfig.zooms"
        :center="mapConfig.center"
        @init="handleMapInit"
        @moveend="handleMoveEnd"
        @zoomchange="handleZoomChange"
    >
      <!--   搜索地点标记   -->
      <el-amap-marker
          :position="searchAddressMarker.position"
          :visible="searchAddressMarker.visible"
      />

      <!-- 游记标记 -->
      <el-amap-marker
          v-if="mapMode === 'articles'"
          v-for="(marker, index) in markers"
          :key="'article-' + index"
          :position="marker.position"
          :icon="marker.icon"
          :offset="[-24, -24]"
          @click="handleMarkerClick(marker)"
      >
        <div class="marker-content">
          <img :src="marker.icon.image" alt="">
        </div>
      </el-amap-marker>

      <!-- 灾害标记 -->
      <el-amap-marker
          v-if="mapMode === 'disasters'"
          v-for="(disaster, index) in disasters"
          :key="'disaster-' + index"
          :position="disaster.position"
          :icon="disaster.icon"
          :offset="[-24, -24]"
          @click="handleDisasterClick(disaster)"
      >
        <div class="marker-content disaster-marker">
          <img :src="disaster.icon.image" alt="">
        </div>
      </el-amap-marker>

      <!-- 游记信息窗口 -->
      <el-amap-info-window
          v-if="activeMarker && mapMode === 'articles'"
          :position="activeMarker.position"
          :visible="infoWindowVisible"
          :isCustom="true"
          :autoMove="true"
          :offset="[0, -40]"
      >
        <article-info-window
            :article="activeMarker.article"
            @close="handleCloseInfo"
            @view-detail="openArticleDetail"
        />
      </el-amap-info-window>

      <!-- 灾害信息窗口 -->
      <el-amap-info-window
          v-if="activeDisaster && mapMode === 'disasters'"
          :position="activeDisaster.position"
          :visible="disasterInfoVisible"
          :isCustom="true"
          :autoMove="true"
          :offset="[0, -40]"
      >
        <disaster-info-window
            :disaster="activeDisaster.data"
            @close="handleCloseDisasterInfo"
        />
      </el-amap-info-window>
    </el-amap>

    <div v-if="showArticleDetail" class="article-modal-overlay" @click.self="closeArticleDetail">
      <ArticleDetail
        :article-id="currentArticleId"
        @close="closeArticleDetail"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue'
import ArticleInfoWindow from './ArticleInfoWindow.vue'
import DisasterInfoWindow from './DisasterInfoWindow.vue'
import ArticleDetail from '@/components/ArticleDetail.vue'
import { TravelMapApi } from '@/api/new/TravelMapApi.js'
import { TravelNoteApi } from '@/api/new/travelNoteApi.js'
import UserUtil from '@/utils/User/User.js'
import { ElMessage } from 'element-plus'
import { Search, Location } from '@element-plus/icons-vue'

// 地图模式：articles(游记) 或 disasters(灾害)
const mapMode = ref('articles')

// 地图配置
const mapConfig = reactive({
  zoom: 15,
  zooms: [8, 18],
  center: [121.393603, 31.315929],
})

// 游记标记数据
const markers = reactive([])

// 灾害标记数据 - 改为响应式，由 API 数据填充
const disasters = ref([])

// 灾害图标映射 - 确保每种灾害类型都有对应的图标
const disasterIcons = {
  'landslid': 'https://cdn-icons-png.flaticon.com/512/15330/15330435.png', // 山体滑坡
  'roadflooding': 'https://cdn-icons-png.flaticon.com/512/3242/3242581.png', // 内涝
  'waterbody': 'https://cdn-icons-png.flaticon.com/512/2352/2352851.png', // 水体
  'road_collapse': 'https://cdn-icons-png.flaticon.com/512/7965/7965577.png', // 路面塌陷
  'road_frozing': 'https://cdn-icons-png.flaticon.com/512/5013/5013351.png', // 路面结冰
  '默认': 'https://cdn-icons-png.flaticon.com/512/1041/1041728.png' // 默认灾害图标 (警告标志)
}

// 灾害类型映射表 - 添加英文到中文的映射
const hazardTypeMap = {
  'landslid': '山体滑坡',
  'roadflooding': '内涝',
  'waterbody': '水体',
  'road_collapse': '路面塌陷',
  'road_frozing': '路面结冰'
};

// 当前激活的游记标记
const activeMarker = ref(null)
const infoWindowVisible = ref(false)

// 当前激活的灾害标记
const activeDisaster = ref(null)
const disasterInfoVisible = ref(false)

// 地图实例
let mapInstance: any = null
let AMapSearch = null; // 搜索服务

// 搜索地址
const searchKeyword = ref('')
// 搜索marker
const searchAddressMarker = ref<any>({
  position: [0, 0],
  visible: false,
})

// 搜索相关
const searching = ref(false);
const searchResults = ref([]);

// 存储游记数据
const travelNotes = ref([]);

// 文章详情模态窗口状态
const showArticleDetail = ref(false);
const currentArticleId = ref(null);

// 添加定位状态
const locating = ref(false);

// 添加防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};



// 地图移动或缩放时触发
const handleMapMoveEnd = () => {
  if (!mapInstance) return;

  // 获取当前地图边界
  const bounds = mapInstance.getBounds();
  const southWest = bounds.getSouthWest();
  const northEast = bounds.getNorthEast();

  console.log('地图边界变化:', southWest, northEast);

  // 使用防抖函数获取标记
  fetchMarkersInBoundsDebounced(
    [southWest.lng, southWest.lat],
    [northEast.lng, northEast.lat]
  );
};

// 地图初始化回调
const handleMapInit = (map: any) => {
  console.log('地图初始化完成', map);
  mapInstance = map; // 保存地图实例

  // 初始化搜索服务
  if (window.AMap && window.AMap.plugin) {
    window.AMap.plugin('AMap.PlaceSearch', () => {
      AMapSearch = new window.AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1,
      });
      console.log('搜索服务初始化成功');
    });
  } else {
    console.error('AMap 插件未加载');
  }

  // 获取用户当前位置
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { longitude, latitude } = position.coords;
        console.log('获取到了用户的经纬度', position.coords)
        mapConfig.center = [longitude, latitude];
        if (mapInstance) {
          mapInstance.setCenter([longitude, latitude]);
        }
      },
      (error) => {
        console.error('获取位置失败:', error);
      }
    );
  }

  // 地图加载完成后绑定事件
  mapInstance.on('moveend', handleMapMoveEnd);
  mapInstance.on('zoomend', handleMapMoveEnd);
}

// 监听地图模式变化
watch(mapMode, (newMode, oldMode) => {
  console.log(`地图模式从 ${oldMode} 切换到 ${newMode}`);

  // 清空信息窗口状态
  handleCloseInfo();
  handleCloseDisasterInfo();

  // 清空标记数据
  markers.splice(0, markers.length);
  disasters.value = [];

  // 重置激活状态
  activeMarker.value = null;
  activeDisaster.value = null;

  // 重置信息窗口状态
  infoWindowVisible.value = false;
  disasterInfoVisible.value = false;

  // 重置文章详情状态
  showArticleDetail.value = false;
  currentArticleId.value = null;

  // 根据新模式获取数据
  if (newMode === 'articles') {
    fetchMarkersInBounds();
  } else if (newMode === 'disasters') {
    fetchDisastersInBounds();
  }
})

// 搜索处理
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }

  searching.value = true;
  searchResults.value = [];

  if (AMapSearch) {
    AMapSearch.search(searchKeyword.value, (status, result) => {
      searching.value = false;

      if (status === 'complete' && result.info === 'OK') {
        searchResults.value = result.poiList.pois || [];

        // 清空旧的标记和信息窗口状态
        activeMarker.value = null;
        infoWindowVisible.value = false;
        markers.splice(0, markers.length); // 清空旧的标记

        // 更新地图标记
        markers.push(...result.poiList.pois.map(poi => ({
          position: [poi.location.lng, poi.location.lat],
          icon: {
            size: [48, 48],
            image: 'https://via.placeholder.com/48', // 使用默认图片或从API获取
            anchor: 'bottom-center'
          },
          article: {
            title: poi.name,
            content: poi.address,
            // 其他文章信息
          }
        })));
      } else {
        ElMessage.warning('搜索结果为空，请尝试其他关键词');
      }
    });
  } else {
    searching.value = false;
    ElMessage.error('搜索服务初始化失败');
  }
};

// 选择搜索结果
const handleSelectSearchResult = (item) => {
  if (item && item.location) {
    const { lng, lat } = item.location;

    console.log(`设置标记位置: [${lng}, ${lat}]`);

    // 更新搜索标记位置
    searchAddressMarker.value.position = [lng, lat];
    searchAddressMarker.value.visible = true;

    // 更新地图中心
    mapConfig.center = [lng, lat];

    // 确保地图中心移动到选择的位置
    if (mapInstance) {
      mapInstance.setCenter([lng, lat]);
    }

    // 清空搜索结果
    searchResults.value = [];
  }
};

// 地图拖拽结束事件
const handleMoveEnd = (e: any) => {
  console.log('地图拖拽结束');

  // 清空信息窗口状态
  handleCloseInfo();
  handleCloseDisasterInfo();

  if (mapMode.value === 'articles') {
    fetchMarkersInBoundsDebounced();
  } else {
    fetchDisastersInBoundsDebounced();
  }
};

// 地图缩放事件
const handleZoomChange = (e: any) => {
  console.log('地图缩放变化');

  // 清空信息窗口状态
  handleCloseInfo();
  handleCloseDisasterInfo();

  if (mapMode.value === 'articles') {
    fetchMarkersInBoundsDebounced();
  } else {
    fetchDisastersInBoundsDebounced();
  }
};

// 获取当前地图可视范围内的游记标记
const fetchMarkersInBounds = async () => {
  if (!mapInstance) return;

  // 获取地图的可视范围 bounds
  const bounds = mapInstance.getBounds();
  const southWest = bounds.getSouthWest(); // 西南角坐标
  const northEast = bounds.getNorthEast(); // 东北角坐标

  const boundsData = {
    southWest: [southWest.lng, southWest.lat],
    northEast: [northEast.lng, northEast.lat]
  };

  console.log('当前地图可视范围:', boundsData);

  // 调用后端接口获取游记标记数据
  await fetchNearbyTravelNotes(boundsData.southWest, boundsData.northEast);
};

// 获取当前地图可视范围内的灾害标记
const fetchDisastersInBounds = async () => {
  if (!mapInstance) return;

  // 获取地图的可视范围 bounds
  const bounds = mapInstance.getBounds();
  const southWest = bounds.getSouthWest(); // 西南角坐标
  const northEast = bounds.getNorthEast(); // 东北角坐标

  const boundsData = {
    southWest: [southWest.lng, southWest.lat],
    northEast: [northEast.lng, northEast.lat]
  };

  console.log('当前地图可视范围(灾害):', boundsData);

  // 调用后端接口获取灾害标记数据
  await fetchNearbyDisasters(boundsData.southWest, boundsData.northEast);
};

// 获取附近灾害
const fetchNearbyDisasters = async (southWest: [number, number], northEast: [number, number]) => {
  // 清空旧的信息窗口状态
  handleCloseDisasterInfo();

  try {
    const response = await TravelMapApi.getNearbyDisasters(
      southWest[1], // minLatitude
      northEast[1], // maxLatitude
      southWest[0], // minLongitude
      northEast[0], // maxLongitude
      '' // 你已经在 axios 中处理了 token
    );
    console.log('获取到的灾害数据:', response);

    // 处理灾害数据，转换为地图标记
    const newDisasters = response.map(disaster => {
      // 根据灾害类型选择对应的图标，如果没有匹配则使用默认图标
      const iconUrl = getDisasterIcon(disaster.disasterType);

      console.log(`灾害类型: ${disaster.disasterType}, 使用图标: ${iconUrl}`); // 调试日志

      // 计算灾害级别
      const level = getDisasterLevel(disaster.disasterType);

      // 使用原始数据，并添加一些用于显示的辅助字段
      return {
        position: [disaster.longitude, disaster.latitude],
        icon: {
          size: [48, 48],
          image: iconUrl,
          anchor: 'bottom-center'
        },
        data: {
          ...disaster, // 保留所有原始字段
          title: `${getDisasterTypeName(disaster.disasterType)} 预警`, // 使用中文名称
          level: level,
          // 如果没有日期，使用当前日期
          date: disaster.date || new Date().toLocaleDateString()
        }
      };
    });

    // 更新灾害标记数组
    disasters.value = newDisasters;
    console.log('更新后的灾害标记:', disasters.value);

  } catch (error) {
    console.error('获取附近灾害失败:', error);
    ElMessage.error(`获取附近灾害失败: ${error.message || '未知错误'}`);
    // 出错时也清空标记，避免显示旧数据
    disasters.value = [];
  }
};

// 获取灾害类型的中文名称
const getDisasterTypeName = (type) => {
  return hazardTypeMap[type] || type;
};

// 根据灾害类型获取灾害级别（可以根据实际需求调整）
const getDisasterLevel = (disasterType) => {
  const levelMap = {
    'landslid': '严重',
    'roadflooding': '严重',
    'waterbody': '严重',
    'road_collapse': '严重',
    'road_frozing': '严重'
  };
  return levelMap[disasterType] || '一般';
};

// 获取灾害图标
const getDisasterIcon = (type) => {
  return disasterIcons[type] || disasterIcons['默认'];
};

// 修正游记标记点击处理函数
const handleMarkerClick = (marker: any) => {
  console.log('标记被点击:', marker);
  console.log('标记位置:', marker.position);
  console.log('标记文章信息:', marker.article);

  // 确保使用正确的文章信息
  const clickedArticle = marker.article;
  if (!clickedArticle) {
    console.error('标记没有关联的文章信息');
    return;
  }

  // 设置当前激活的标记
  activeMarker.value = {
    ...marker,
    article: clickedArticle // 确保文章信息正确传递
  };

  // 显示信息窗口
  infoWindowVisible.value = true;

  console.log('当前激活的标记:', activeMarker.value);
  console.log('信息窗口可见状态:', infoWindowVisible.value);
};

// 灾害标记点击处理
const handleDisasterClick = (disaster: any) => {
  activeDisaster.value = disaster
  disasterInfoVisible.value = true
}

// 关闭游记信息窗口
const handleCloseInfo = () => {
  infoWindowVisible.value = false;
  activeMarker.value = null;
  // 确保文章详情也被关闭
  showArticleDetail.value = false;
  currentArticleId.value = null;
};

// 关闭灾害信息窗口
const handleCloseDisasterInfo = () => {
  disasterInfoVisible.value = false;
  activeDisaster.value = null;
};

// 获取附近游记函数修正
const fetchNearbyTravelNotes = async (southWest: [number, number], northEast: [number, number]) => {
  try {
    // 清空现有标记和信息窗口状态
    markers.splice(0, markers.length);
    handleCloseInfo();

    const token = 'your-auth-token'; // 替换为实际的用户身份验证 token
    const response = await TravelMapApi.getNearbyTravelNotes(
      southWest[1], // minLatitude
      northEast[1], // maxLatitude
      southWest[0], // minLongitude
      northEast[0], // maxLongitude
      token
    );
    console.log('获取到的游记数据:', response);

    // 获取每篇游记的图片
    const notesWithImages = await Promise.all(response.map(async (note) => {
      try {
        const imageData = await TravelNoteApi.getFirstImage(note.articleID);
        return {
          ...note,
          imageUrl: imageData?.imageUrl || 'https://via.placeholder.com/48',
          formattedDate: new Date(note.creationTime).toLocaleDateString(),
          // 确保经纬度信息正确
          longitude: note.longitude,
          latitude: note.latitude
        };
      } catch (error) {
        console.error(`获取游记 ${note.articleID} 图片失败:`, error);
        return {
          ...note,
          imageUrl: 'https://via.placeholder.com/48',
          formattedDate: new Date(note.creationTime).toLocaleDateString(),
          // 确保经纬度信息正确
          longitude: note.longitude,
          latitude: note.latitude
        };
      }
    }));

    // 更新游记数据
    travelNotes.value = notesWithImages;

    // 添加新标记，确保每个标记都有正确的文章信息
    notesWithImages.forEach(note => {
      // 确保经纬度有效
      if (!note.longitude || !note.latitude) {
        console.warn(`游记 ${note.articleID} 缺少有效的经纬度信息`);
        return;
      }

      // 创建标记对象
      const marker = {
        position: [note.longitude, note.latitude],
        icon: {
          size: [48, 48],
          image: note.imageUrl,
          anchor: 'bottom-center'
        },
        article: { ...note } // 使用展开运算符创建文章对象的副本
      };

      // 添加到标记数组
      markers.push(marker);
    });

    console.log('更新后的标记:', markers);
  } catch (error) {
    console.error('获取附近游记失败:', error);
    ElMessage.error(`获取附近游记失败: ${error.message || '未知错误'}`);
  }
};

// 打开文章详情
const openArticleDetail = (articleId) => {
  currentArticleId.value = articleId;
  showArticleDetail.value = true;
  // 禁止背景滚动
  document.body.style.overflow = 'hidden';
};

// 关闭文章详情
const closeArticleDetail = () => {
  showArticleDetail.value = false;
  // 恢复背景滚动
  document.body.style.overflow = '';
};

// 定位到当前位置的函数
const locateCurrentPosition = () => {
  if (!navigator.geolocation) {
    ElMessage.warning('您的浏览器不支持地理定位');
    return;
  }

  locating.value = true;

  navigator.geolocation.getCurrentPosition(
    (position) => {
      const { longitude, latitude } = position.coords;
      console.log('获取到了用户的经纬度', position.coords);

      // 更新地图中心
      mapConfig.center = [longitude, latitude];
      if (mapInstance) {
        mapInstance.setCenter([longitude, latitude]);

        // 可选：调整缩放级别
        mapInstance.setZoom(16);
      }

      locating.value = false;
      ElMessage.success('已定位到当前位置');
    },
    (error) => {
      locating.value = false;
      console.error('获取位置失败:', error);

      let errorMessage = '获取位置失败';
      switch (error.code) {
        case error.PERMISSION_DENIED:
          errorMessage = '您拒绝了位置请求，请在浏览器设置中允许位置访问';
          break;
        case error.POSITION_UNAVAILABLE:
          errorMessage = '位置信息不可用';
          break;
        case error.TIMEOUT:
          errorMessage = '获取位置超时';
          break;
      }

      ElMessage.error(errorMessage);
    },
    {
      enableHighAccuracy: true, // 尝试获取更精确的位置
      timeout: 10000, // 10秒超时
      maximumAge: 0 // 不使用缓存的位置
    }
  );
};
// 为地图边界变化事件添加防抖
const fetchMarkersInBoundsDebounced = debounce(fetchMarkersInBounds, 300);
// 为灾害获取也添加防抖
const fetchDisastersInBoundsDebounced = debounce(fetchDisastersInBounds, 300);
// 在组件挂载时调用
onMounted(() => {
  fetchMarkersInBounds();
});
</script>

<style lang="less" scoped>
.map-container {
  width: calc(100% - 50px);
  height: calc(98vh - 72px);
  position: relative;
  margin-left: 30px;

  // 切换按钮样式
  .map-toggle {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 10;
    background-color: white;
    padding: 5px;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .amap-box {
    height: 100%;
    position: relative;
  }

  // 搜索框样式
  .search-box {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 999;
    background-color: #fff;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    width: 380px;
    display: flex;
    align-items: center;

    .location-button-container {
      margin-right: 10px;

      .el-button {
        background-color: white;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);

        &:hover {
          background-color: #f5f5f5;
        }
      }
    }

    .el-input {
      flex: 1;
    }

    .search-results {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background: white;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      max-height: 300px;
      overflow-y: auto;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-top: 5px;

      .search-result-item {
        padding: 10px 15px;
        cursor: pointer;
        border-bottom: 1px solid #f0f0f0;

        &:hover {
          background-color: #f5f7fa;
        }

        &:last-child {
          border-bottom: none;
        }

        .result-name {
          display: block;
          font-weight: bold;
          margin-bottom: 3px;
        }

        .result-address {
          display: block;
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }

  // 默认标记样式
  :deep(.amap-marker) {
    transition: transform 0.3s ease;

    &:hover {
      transform: scale(1.1);
      cursor: pointer;
    }
  }

  // 自定义标记样式
  :deep(.marker-content) {
    width: 48px;
    height: 48px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      border: 2px solid #fff;
    }

    &.disaster-marker img {
      border-color: #ff4d4f;
    }
  }

  .article-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000; // 提高 z-index 确保在其他元素之上
  }
}

// 确保灾害标记样式正确
.disaster-marker img {
  width: 48px;
  height: 48px;
  border: 2px solid #ff4d4f;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 8px rgba(255, 77, 79, 0.6);
}

.nearby-list {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 15px;
  margin-top: 20px;
  max-height: 400px;
  overflow-y: auto;

  h1 {
    font-size: 18px;
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
  }

  ul {
    list-style: none;
    padding: 0;

    li {
      padding: 10px 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      h2 {
        font-size: 16px;
        margin-bottom: 5px;
      }

      p {
        font-size: 14px;
        color: #666;
        margin: 3px 0;
      }
    }
  }
}
</style>
